<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用finally实现异步加载动画</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: red;
            color: white;
            display: none;
        }
    </style>
</head>
<body>
    <div id="loading">loading...</div>
    <script>
        // new Promise((resolve,reject) => {
        //     // resolve("成功");
        //     reject("失败");
        // }).then(
        //     value => {
        //         console.log(value);
        //     },
        //     reason => {
        //         console.log(reason);
        //     }
        // )
        // .finally(() => console.log("无论成功还是失败，都会打印")) //无论成功还是失败，finally中的内容都会打印


        class ParamError extends Error{
            constructor(msg){
                super(msg);
                this.name = "paramError";
            }
        }

        class HttpError extends Error{
            constructor(msg){
                super(msg);
                this.name = "httpError";
            }
        }

        function ajax(url){
            return new Promise((resolve,reject) => {
                loading.style.display = "block";

                if(!/^http/.test(url)){
                    throw new ParamError("请求地址格式错误");
                }

                let xhr = new XMLHttpRequest();
                xhr.open("GET",url);
                xhr.send();
                xhr.onload = function(){
                    if(this.status == 200){
                        resolve(JSON.parse(this.response));
                    }else if(this.status == 404){
                        reject(new HttpError("请求参数错误"));
                    }else{
                        reject("加载失败");
                    }
                };
                xhr.onerror = function (){
                    reject(this);
                }
            })
        }

        let url = "https://localhost:8888/php";
        ajax(`${url}/user.php?username = 后盾人`)
        .then(user => ajax(`${url}/houdunren.php?id=${user.id}`))
        .then(lesson => console.log(lesson))
        .catch(
            error => {
                if(errror instanceof ParamError){
                    console.log(error.message);
                }
                
                if(error instanceof HttpError){
                    alert(error.message);
                }
            }
        ).finally(
            () => {
                loading.style.display = "none";
            }
        );
    </script>
</body>
</html>